package com.lesshassles.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.lesshassles.model.Task;
import com.lesshassles.model.TaskBroker;
import com.lesshassles.model.User;
import com.lesshassles.model.UserBroker;
import com.lesshassles.util.ApplicationSecurityManager;
import com.lesshassles.util.UserPropertyEditor;

public class TaskCreateController extends SimpleFormController {
	private TaskBroker taskBroker;
	private UserBroker userBroker;
	private ApplicationSecurityManager applicationSecurityManager;
	
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Task task = new Task();
		
		return task;	
	}
	
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(User.class, new UserPropertyEditor(userBroker));
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
		super.initBinder(request, binder);
	}

	/** returns ModelAndView(getSuccessView()) */
	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Task task = (Task)command;
		try {
			task = taskBroker.save(task);
		} catch(Exception ex) {
			errors.reject("error.database.general");
			return showForm(request, response, errors);
		}

		String successView = getSuccessView().replace("{0}", "" + task.getId());
		return new ModelAndView(successView);
	}
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
		ModelMap model = new ModelMap("users", userBroker.getUsers());
		return model;
	}

	public TaskBroker getTaskBroker() {
		return taskBroker;
	}

	public void setTaskBroker(TaskBroker taskBroker) {
		this.taskBroker = taskBroker;
	}

	public ApplicationSecurityManager getApplicationSecurityManager() {
		return applicationSecurityManager;
	}

	public void setApplicationSecurityManager(ApplicationSecurityManager applicationSecurityManager) {
		this.applicationSecurityManager = applicationSecurityManager;
	}

	public UserBroker getUserBroker() {
		return userBroker;
	}

	public void setUserBroker(UserBroker userBroker) {
		this.userBroker = userBroker;
	}

}
